import { IOneModalRef } from '@/pages/type';
import { getColorTextLoadMap, getFileNameByPath, onCloseModalCommon, removeDateHmsStr } from '@/utils';
import { Ref, useRef, useState } from 'react';
import { OneModal } from '@/components/one-ui';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons';
import { Form, Row, Col, Input, Button, Table, Spin, Tooltip } from 'antd';
import { templateManageService } from '../services/ContractModal';
import { SeeTemplateInfoModal } from '@/pages/ContractController/TemplateManage/mview/SeeTemplateInfoModal';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import { ColumnsRenderFun } from '../../Acommon';
import '../common/style.less';
const prefixCls = 'documentatio-update';
const ContractModal = ({ onSave, onClose, curRes }: Record<string, any>) => {
  /**弹窗Ref*/
  const oneModalRef: Ref<IOneModalRef> = useRef(null);
  // 获取列表数据
  const { data, loading, pagination, searchList, getTempContractData, reloadRefresh } = templateManageService(curRes);

  /** 查看使用说明 */
  const [openSeeTempInfoStr, setOpenSeeTempInfoStr] = useState<Record<string, any>>({
    isShowModal: false,
    checkRowsInfo: {},
  });
  const onSeeInfo = (record: any) => {
    setOpenSeeTempInfoStr({
      isShowModal: true,
      checkRowsInfo: record,
    });
  };
  const columns = [
    {
      title: '范本名称',
      dataIndex: 'fullName',
      key: 'fullName',
      width: 200,
      render: (text) => ColumnsRenderFun({ text }),
    },
    {
      title: '范本文本',
      dataIndex: 'templateURL',
      key: 'templateURL',
      width: 400,
      render: (text: string | null, record: Record<string, any>) => {
        const fileName: string = getFileNameByPath(text);
        return (
          <>
            {text ? (
              <Tooltip title={fileName}>
                <a>
                  <MyIcon type="icon-file-text-fill" />
                  &nbsp;
                  {fileName}
                </a>
              </Tooltip>
            ) : (
              <>--</>
            )}
          </>
        );
      },
    },
    {
      title: '合同类型',
      dataIndex: 'businessTypeName',
      key: 'businessTypeName',
      width: 200,
      render: (text: string | null) => {
        const { colorText } = getColorTextLoadMap(text);
        return <span className={pageStyles['over-flow-hidden']}>{colorText ? colorText : '--'}</span>;
      },
    },
    {
      title: '范本描述',
      dataIndex: 'templateInfo',
      key: 'templateInfo',
      width: 200,
      render: (text: string | null, record: Record<string, any>) => {
        return (
          <a
            style={{ color: '#ea0000' }}
            onClick={() => {
              onSeeInfo(record);
            }}
          >
            使用说明
          </a>
        );
      },
    },
    {
      title: '发布人',
      dataIndex: 'signerName',
      key: 'signerName',
      width: 150,
      render: (text) => ColumnsRenderFun({ text }),
    },
    {
      title: '发布时间',
      dataIndex: 'signTime',
      key: 'signTime',
      width: 150,
      render: (text: string) => {
        const dateText: string = removeDateHmsStr(text);
        return <span className={pageStyles['over-flow-hidden']}>{dateText}</span>;
      },
    },
  ];

  // 选中表格id集合
  const [selectedRow, setSelectedRow] = useState<Record<string, any>>([]);

  /**确认*/
  const onModalOk = () => {
    onSave(selectedRow);
    onCloseModalCommon(oneModalRef);
  };

  /**
   * 表单Form
   * */
  const [searchForm] = Form.useForm();

  /**
   * @onSelectChange 复选框change事件
   * @param keys 表格ID
   * */
  const onSelectChange = (_: React.Key[], rows: Record<string, any>) => setSelectedRow(rows);

  // 底部按钮
  const footerRender = () => {
    return (
      <>
        <Button onClick={() => onCloseModalCommon(oneModalRef)}>取消</Button>
        <Button type={'primary'} onClick={onModalOk}>
          确认
        </Button>
      </>
    );
  };
  // 搜索
  const onSearch = () => {
    getTempContractData({ fullName: searchForm.getFieldValue('fullName'), templateInfo: searchForm.getFieldValue('templateInfo') });
  };
  /**  重置搜索表单方法 */
  const onReset = (values: any) => {
    searchForm.resetFields();
    getTempContractData({ fullName: searchForm.getFieldValue('fullName'), templateInfo: searchForm.getFieldValue('templateInfo') });
  };
  // 分页
  const handlePageChange = (current: any, pageSize: any): any => {
    getTempContractData({ pageSize, current });
  };
  const paginations = {
    // 分页配置
    pageSize: pagination.pageSize, // 每页显示的条数
    showSizeChanger: true, // 是否可以改变每页显示的条数
    pageSizeOptions: ['5', '10', '15', '20'], // 可选的每页显示条数
    showQuickJumper: true, // 是否可以快速跳转到指定页
    showTotal: () => `共 ${pagination.total} 条`, // 显示总条数和当前数据范围
    current: pagination.current, // 当前页数
    total: pagination.total, // 总条数
    onChange: handlePageChange, // 页码改变时的回调函数
  };
  return (
    <div>
      <OneModal
        open={true}
        onCancel={onClose}
        centered={true}
        title={'选择合同范本'}
        bodyStyle={{
          height: '600px',
          padding: '5px 0px',
        }}
        width={document.body.clientWidth * 0.6}
        ref={oneModalRef}
        footer={footerRender()}
      >
        <Spin spinning={loading}>
          <div className={`${prefixCls}-ContractBox`}>
            <div>
              <Form form={searchForm}>
                <Row gutter={[8, 0]} style={{ padding: '10px 1rem 0' }}>
                  <Col span={4}>
                    <Form.Item name="fullName">
                      <Input placeholder="范本名称" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={4}>
                    <Form.Item name="templateInfo">
                      <Input placeholder="范本描述" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={16} style={{ textAlign: 'right' }}>
                    <Button style={{ margin: '0 7px' }} type="primary" icon={<SearchOutlined />} onClick={onSearch}>
                      查询
                    </Button>
                    <Button icon={<RedoOutlined />} onClick={onReset}>
                      重置
                    </Button>
                  </Col>
                </Row>
              </Form>
            </div>
            <div className={'list-table'}>
              <Table
                bordered
                size="small"
                columns={columns}
                dataSource={data?.rows}
                loading={false}
                scroll={{ x: 500, y: 500 }}
                rowKey={(record: any) => record?.id}
                rowSelection={{
                  type: 'radio',
                  onChange: onSelectChange,
                }}
                pagination={paginations}
              ></Table>
            </div>
          </div>
        </Spin>
      </OneModal>
      {/* 查看使用说明 */}
      {openSeeTempInfoStr?.isShowModal && (
        <SeeTemplateInfoModal
          onClose={() => {
            setOpenSeeTempInfoStr({
              isShowModal: false,
              checkRowsInfo: {},
            });
          }}
          checkRowsInfo={openSeeTempInfoStr?.checkRowsInfo}
        />
      )}
    </div>
  );
};

export default ContractModal;
